05. DELETE a Todo item - Solution

Delete a Todo Item - Solution

index.html
<ul id="todos">
  {% for todo in todos %}
  <li>
    <input class="check-completed" data-id="{{ todo.id }}" type="checkbox" {% if todo.completed %} checked {% endif %} />
    {{ todo.description }}
    <button class="delete-button" data-id="{{ todo.id }}">&cross;</button>
  </li>
  {% endfor %}
</ul>

In <script>...</script> located near the end of the body ,

const deleteBtns = document.querySelectorAll('.delete-button');
  for (let i = 0; i < deleteBtns.length; i++) {
    const btn = deleteBtns[i];
    btn.onclick = function(e) {
      const todoId = e.target.dataset['id'];
      fetch('/todos/' + todoId, {
        method: 'DELETE'
      });
    }
  }
app.py
@app.route('/todos/<todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
  try:
    Todo.query.filter_by(id=todo_id).delete()
    db.session.commit()
  except:
    db.session.rollback()
  finally:
    db.session.close()
  return jsonify({ 'success': True })

Solution Code

Download the solution by clicking here: todoapp-updates-deletes.zip

To run it:

$ pip3 install -r requirements.txt
$ FLASK_APP=app.py FLASK_DEBUG=true flask run